<?php

require_once ROOT . '/db/MenuEntity.php';
require_once ROOT . '/db/PageEntity.php';

final class PublicUI {
    private static $smarty;
    private static $url;

    public static function init(Smarty $smarty) {
        self::$smarty = $smarty;
        self::$url = isset($_GET['url']) ? $_GET['url'] : '';
        self::initMenu();
        self::initMenuTree();
        self::initContent();
    }

    private static function initContent() {
        $page = Persistence::load('Page', array('url' => self::$url));
        if (isset($page[0])) {
            self::$smarty->assign($page[0]->dump());
            return;
        }
        $page404 = Persistence::load('Page', array('url' => '404'));
        if (isset($page404[0])) {
            self::$smarty->assign($page404[0]);
        }
    }

    private static function initMenu() {
        $menu = Persistence::load('Menu', array(), array('id'));
        foreach ($menu as &$item) {
            $item = $item->dump();
            $item['href'] = WEB_DIR . '/' . $item['href'];
        }
        self::$smarty->assign('mainmenu', $menu);
    }
    
    private static function initMenuTree() {
        $tree = self::loadMenuTree();
        self::$smarty->assign('mainmenutree', $tree);
    }
    
    private static function loadMenuTree($root = 0, $parentIndex = null) {
        $menu = Persistence::load('Menu', array('parent' => (int) $root),
                array('id'));
        $index = 1;
        foreach ($menu as &$item) {
            $item = $item->dump();
            $item['index'] = $parentIndex ? "$parentIndex.$index" : $index;
            $item['href'] = WEB_DIR . '/' . $item['href'];
            $item['sub'] = self::loadMenuTree($item['id'], $item['index']);
            $index++;
        }
        return $menu;
    }
}
?>
